from rest_framework.viewsets import GenericViewSet
from utils.my_drf.response import APIResponse
from utils.my_drf.admin_auth import AdminJwtAuth
from qiniu import Auth
from django.conf import settings


class GetQiNiuTokenView(GenericViewSet):
    authentication_classes = [AdminJwtAuth, ]

    def list(self, request):
        # 实例化七牛
        q = Auth(settings.QINIU_ACCESS_KEY, settings.QINIU_SECRET_KEY)
        # 要上传的空间
        bucket_name = settings.QINIU_BUCKET_NAME
        # 上传后保存的文件名
        # key_l = time.strftime("%Y%m%d%H%M%S")
        # key_r = str(uuid.uuid4()).replace('-', '')
        # key = '{}{}'.format(key_l, key_r)
        key = None
        # 上传策略示例
        policy = {
            # 'callbackUrl':'https://requestb.in/1c7q2d31',
            # 'callbackBody':'filename=$(fname)&filesize=$(fsize)'
            # 'persistentOps':'imageView2/1/w/200/h/200'
        }
        # 3600为token过期时间，秒为单位。3600等于一小时
        token = q.upload_token(bucket_name, key, 3600, policy)
        return APIResponse(data={'token': token})
